﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace produccion.forms
{
    /// <summary>
    /// Lógica de interacción para FrmReporteProduccionCorte.xaml
    /// </summary>
    public partial class FrmReporteProduccionCorte : Window
    {
        public FrmReporteProduccionCorte()
        {
            InitializeComponent();
        }

        private void cmbTipoSeleccion_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                string strDatoCombo = cmbTipoSeleccion.Text;

                if (strDatoCombo == "Empleados")
                {
                    dtgEmpleados.Focus();
                    dtgEmpleados.CurrentCell = new DataGridCellInfo(dtgEmpleados.Items[0], dtgEmpleados.Columns[0]);
                    dtgEmpleados.BeginEdit();
                }
                if (strDatoCombo == "Equipos")
                {
                    cmbEquipos.Focus();
                }
                
            }
        }

        private void cmbTipoSeleccion_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string strDatoCombo = cmbTipoSeleccion.Text;
            if (strDatoCombo == "Empleados")
            {
                ActivarEquipos();
            }
            if (strDatoCombo == "Equipos")
            {
                ActivarEmpleados();
            }
        }

        private void ReporteProduccion_Loaded(object sender, RoutedEventArgs e)
        {
            txtNumerodeOrde.Style = null;
            txtAReportar.Style = null;
            cmbEquipos.Style = null;

            Keyboard.Focus(txtSemana);
            ActivarEmpleados();

            Style MyStyleDerecha = new Style(typeof(DataGridCell));
            MyStyleDerecha.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));

            Style MyStyleDerecha2 = new Style(typeof(DataGridCell));
            MyStyleDerecha2.Setters.Add(new Setter(TextBlock.TextAlignmentProperty, TextAlignment.Right));

            dtgEmpleados.Columns[2].CellStyle = MyStyleDerecha;

            dtgOrdenesAReportar.Columns[5].CellStyle = MyStyleDerecha2;
        }

        private void dtgOrdenesAReportar_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                var elemento = e.OriginalSource as UIElement;

                if ((e.Key == Key.Enter || e.Key == Key.Return) && elemento != null)
                {
                    string StrDatos1 = "";
                    DataGridCell cell = DataGridHelper.GetCell(dtgOrdenesAReportar, dtgOrdenesAReportar.SelectedIndex, 0);
                    int i = dtgOrdenesAReportar.SelectedIndex;

                    int IntColumna = dtgOrdenesAReportar.CurrentCell.Column.DisplayIndex;
                    StrDatos1 = cell.ToString().Replace("System.Windows.Controls.DataGridCell:", "").Trim();

                    if (cell != null)
                    {
                        if (IntColumna == 0)
                        {
                            if (StrDatos1.Length == 6)
                            {
                                e.Handled = true;
                                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            }
                        }
                        else
                        {
                            dtgOrdenesAReportar.CurrentCell = new DataGridCellInfo(dtgOrdenesAReportar.Items[i], dtgOrdenesAReportar.Columns[0]);
                            dtgOrdenesAReportar.ScrollIntoView(dtgOrdenesAReportar.Items[i]);
                            dtgOrdenesAReportar.BeginEdit();
                        }
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void dtgEmpleados_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                var elemento = e.OriginalSource as UIElement;
                if ((e.Key == Key.Enter || e.Key == Key.Return) && elemento != null)
                {
                    string StrDatos1 = "";
                    DataGridCell cell = DataGridHelper.GetCell(dtgEmpleados, dtgEmpleados.SelectedIndex, 0);
                    int i = dtgEmpleados.SelectedIndex;

                    int IntColumna = dtgEmpleados.CurrentCell.Column.DisplayIndex;
                    StrDatos1 = cell.ToString().Replace("System.Windows.Controls.DataGridCell:", "").Trim();

                    if (cell != null)
                    {
                        if (IntColumna == 0)
                        {
                            if (StrDatos1.Length == 5)
                            {
                                e.Handled = true;
                                elemento.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            }
                        }
                        else
                        {
                            if (txtPorcentaje.Text != "100.00")
                            {
                                dtgEmpleados.CurrentCell = new DataGridCellInfo(dtgEmpleados.Items[i], dtgEmpleados.Columns[0]);
                                dtgEmpleados.ScrollIntoView(dtgEmpleados.Items[i]);
                                dtgEmpleados.BeginEdit();
                            }
                            else
                            {
                                txtNumerodeOrde.Focus();
                            }
                        }
                    }
                }
            }
            catch (Exception ex) 
            {
                if (txtPorcentaje.Text == "100.00")
                {
                    txtNumerodeOrde.Focus();
                }
            }
        }

        private void txtNumerodeOrde_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (txtNumerodeOrde.Text.Trim().Length > 4 )
                {
                    bool isNumber;
                    double isItNumeric=0;
                    isNumber = Double.TryParse(Convert.ToString(txtTotalOrden.Text.Trim()), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out isItNumeric);

                    if (isNumber==true && isItNumeric > 0 )
                    {
                        if (txtNumerodeOrde.Text.Trim().Length == 5)
                            txtAReportar.Text = "0";
                        else
                            txtAReportar.Text = txtPendiente.Text;

                        txtAReportar.Focus();
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void txtNumerodeOrde_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                var elemento = e.OriginalSource as UIElement;
                if (e.Key == Key.Enter && elemento != null)
                {
                    if (txtNumerodeOrde.Text.Trim().Length > 4 )
                    {
                        //if (Convert.ToDouble(txtAReportar.Text.Trim()) > 0)
                        //{
                        //    txtAReportar.Focus();
                        //}
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void txtAReportar_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                var elemento = e.OriginalSource as UIElement;
                if (e.Key == Key.Enter && elemento != null)
                {
                    if (txtAReportar.Text.Trim() != "")
                    {
                        if (Convert.ToDouble(txtAReportar.Text.Trim()) > 0)
                        {
                            if (Convert.ToDouble(txtAReportar.Text.Trim()) <= Convert.ToDouble(txtTotalOrden.Text.Trim()))
                            {
                                txtAReportar2.Text = txtAReportar.Text;
                                txtNumerodeOrde.Focus();
                            }
                        }
                    }
                    else
                        txtNumerodeOrde.Focus();
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void txtAReportar2_TextChanged(object sender, TextChangedEventArgs e)
        {
            txtNumerodeOrde.Focus();
        }

         //
        // SINGLE CLICK EDITING
        //
        private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DataGridCell cell = sender as DataGridCell;
            if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
            {
                if (!cell.IsFocused)
                {
                    cell.Focus();
                }
                DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
                if (dataGrid != null)
                {
                    if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
                    {
                        if (!cell.IsSelected)
                        {
                            cell.IsSelected = true;
                            cell.Focus();
                        }
                    }
                    else
                    {
                        DataGridRow row = FindVisualParent<DataGridRow>(cell);
                        if (row != null && !row.IsSelected)
                        {
                            row.IsSelected = true;
                            row.Focus();
                        }
                    }
                }
            }
        }

        static T FindVisualParent<T>(UIElement element) where T : UIElement
        {
            UIElement parent = element;
            while (parent != null)
            {
                T correctlyTyped = parent as T;
                if (correctlyTyped != null)
                {
                    return correctlyTyped;
                }

                parent = VisualTreeHelper.GetParent(parent) as UIElement;
            }
            return null;
        }

        private void ReporteProduccion_KeyDown(object sender, KeyEventArgs e)
        {
            var elemento = e.OriginalSource as UIElement;
            if (e.Key == Key.F3 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta == true) { MDOgeneral.logBusquedadAbierta = false; }
            }

            if (e.Key == Key.F4 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta1 == true) { MDOgeneral.logBusquedadAbierta1 = false; }
            }

            if (e.Key == Key.F5 && elemento != null)
            {
                if (MDOgeneral.logBusquedadAbierta2 == true) { MDOgeneral.logBusquedadAbierta2 = false; }
            }
        }

        private void ActivarEquipos()
        {
            Espacio1.Visibility = Visibility.Visible;
            txbEquipos.Visibility = Visibility.Visible;
            Espacio2.Visibility = Visibility.Visible;
            Espacio3.Visibility = Visibility.Collapsed;
            cmbEquipos.Visibility = Visibility.Visible;
            txbPorcentaje.Visibility = Visibility.Visible;
            txtPorcentaje.Visibility = Visibility.Visible;
            txtPorcentaje.IsReadOnly = true;
            txbTituloGridEmpleados.Visibility = Visibility.Visible;
            dtgEmpleados.Visibility = Visibility.Visible;
            dtgEmpleados.IsReadOnly = true;
        }

        private void ActivarEmpleados()
        {
            Espacio1.Visibility = Visibility.Collapsed;
            txbEquipos.Visibility = Visibility.Collapsed;
            Espacio2.Visibility = Visibility.Collapsed;
            Espacio3.Visibility = Visibility.Visible;
            cmbEquipos.Visibility = Visibility.Collapsed;
            txbPorcentaje.Visibility = Visibility.Visible;
            txtPorcentaje.Visibility = Visibility.Visible;
            txtPorcentaje.IsReadOnly = true;
            txbTituloGridEmpleados.Visibility = Visibility.Visible;
            dtgEmpleados.Visibility = Visibility.Visible;
            dtgEmpleados.IsReadOnly = false;
        }

        private void btnNuevo_Click(object sender, RoutedEventArgs e)
        {
            cmbProcesos.SelectedIndex = -1;
            cmbTipoSeleccion.SelectedIndex = 0;
            cmbEquipos.SelectedIndex = -1;
            txtSemana.Focus();
        }

        private void btnGuardar_Click(object sender, RoutedEventArgs e)
        {
            cmbTipoSeleccion.SelectedIndex = 0;
            txtSemana.Focus();
        }

        private void cmbProceso_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //Keyboard.Focus(cmbTipoSeleccion);
            }
        }

        private void cmbEquipos_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (cmbEquipos.SelectedIndex != -1)
                    txtNumerodeOrde.Focus();
            }
        }


        //
        private void SelectAddress(object sender, RoutedEventArgs e)
        {
            TextBox tb = (sender as TextBox);
            if (tb != null)
            {
                tb.SelectAll();
            }
        }



        private void SelectivelyIgnoreMouseButton(object sender,MouseButtonEventArgs e)
        {
            TextBox tb = (sender as TextBox);
            if (tb != null)
            {
                if (!tb.IsKeyboardFocusWithin)
                {
                    e.Handled = true;
                    tb.Focus();
                }
            }
        }
        //

        #region ParaObtenerLasPropiedadesDeLaCeldaDelGrid
        static class DataGridHelper
        {
            static public DataGridCell GetCell(DataGrid dg, int row, int column)
            {
                DataGridRow rowContainer = GetRow(dg, row);

                if (rowContainer != null)
                {
                    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

                    // try to get the cell but it may possibly be virtualized
                    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                    if (cell == null)
                    {
                        // now try to bring into view and retreive the cell
                        dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                    }
                    return cell;
                }
                return null;
            }

            static public DataGridRow GetRow(DataGrid dg, int index)
            {
                DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
                if (row == null)
                {
                    // may be virtualized, bring into view and try again
                    dg.ScrollIntoView(dg.Items[index]);
                    row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
                }
                return row;
            }

            static T GetVisualChild<T>(Visual parent) where T : Visual
            {
                T child = default(T);
                int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < numVisuals; i++)
                {
                    Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                    child = v as T;
                    if (child == null)
                    {
                        child = GetVisualChild<T>(v);
                    }
                    if (child != null)
                    {
                        break;
                    }
                }
                return child;
            }
        }
        #endregion


        #region FJRF - FuncionesEspecialesParaLasPropiedadesDeLaCeldaYElFoco

        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T)
                    return (T)child;
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        public static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
        {
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                if (presenter == null)
                {
                    /* if the row has been virtualized away, call its ApplyTemplate() method 
                     * to build its visual tree in order for the DataGridCellsPresenter
                     * and the DataGridCells to be created */
                    rowContainer.ApplyTemplate();
                    presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
                }
                if (presenter != null)
                {
                    DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    if (cell == null)
                    {
                        /* bring the column into view
                         * in case it has been virtualized away */
                        dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
                        cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
                    }
                    return cell;
                }
            }
            return null;
        }
        public static void SelectRowByIndexes(DataGrid dataGrid, params int[] rowIndexes)
        {
            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.FullRow))
                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to FullRow.");

            if (!dataGrid.SelectionMode.Equals(DataGridSelectionMode.Extended))
                throw new ArgumentException("The SelectionMode of the DataGrid must be set to Extended.");

            if (rowIndexes.Length.Equals(0) || rowIndexes.Length > dataGrid.Items.Count)
                throw new ArgumentException("Invalid number of indexes.");

            dataGrid.SelectedItems.Clear();
            foreach (int rowIndex in rowIndexes)
            {
                if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
                    throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));

                object item = dataGrid.Items[rowIndex]; //=Product X
                dataGrid.SelectedItems.Add(item);

                DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
                if (row == null)
                {
                    dataGrid.ScrollIntoView(item);
                    row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
                }
                if (row != null)
                {
                    DataGridCell cell = GetCell(dataGrid, row, 0);
                    if (cell != null)
                        cell.Focus();
                }
            }
        }
        public static void SelectCellByIndex(DataGrid dataGrid, int rowIndex, int columnIndex)
        {
            if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.Cell))
                throw new ArgumentException("The SelectionUnit of the DataGrid must be set to Cell.");

            if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
                throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));

            if (columnIndex < 0 || columnIndex > (dataGrid.Columns.Count - 1))
                throw new ArgumentException(string.Format("{0} is an invalid column index.", columnIndex));

            dataGrid.SelectedCells.Clear();

            object item = dataGrid.Items[rowIndex]; //=Product X
            DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            if (row == null)
            {
                dataGrid.ScrollIntoView(item);
                row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
            }
            if (row != null)
            {
                DataGridCell cell = GetCell(dataGrid, row, columnIndex);
                if (cell != null)
                {
                    DataGridCellInfo dataGridCellInfo = new DataGridCellInfo(cell);
                    dataGrid.SelectedCells.Add(dataGridCellInfo);

                    cell.Focus();
                }
            }
        }
        #endregion

        

     }
}
